﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using CentralOffice.PublicAffair.Data;
using CentralOffice.PublicAffair.BusinessActions;

using NoticeTable = CentralOffice.PublicAffair.Data.NoticeDataSet.NotificationsDataTable;
using NoticeRow = CentralOffice.PublicAffair.Data.NoticeDataSet.NotificationsRow;
using Husb.Util;
using Husb.Util.Enum;


using CentralOffice.MyTable.Data;
using CentralOffice.MyTable.BusinessActions;
using Husb.Security;
using CentralOffice.Admin.BusinessActions;

using SmsTable = CentralOffice.MyTable.Data.SmsDataSet.smsDataTable;
using SmsRow = CentralOffice.MyTable.Data.SmsDataSet.smsRow;
using SmsBodyTable = CentralOffice.MyTable.Data.SmsDataSet.sms_bodyDataTable;
using SmsBodyRow = CentralOffice.MyTable.Data.SmsDataSet.sms_bodyRow;




namespace CentralOffice.WebClient.PublicAffairs
{
    public partial class NoticeEdit : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                SiteUtil.PopulateListBox(ddlSignificant, SiteConstants.Significant, false);
                //if (ddlSignificant.Items.Count > 1)
                //{
                //    ddlSignificant.SelectedIndex = 1;
                //}
                //else
                //{
                //    ddlSignificant.SelectedIndex = 0;
                //}
                SetFields(HttpContext.Current.Request.QueryString["id"]);
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            //string s = txtContentText.Value;

            Guid id = this.Save();
            Response.Redirect("~/PublicAffairs/NoticeView.aspx?id=" + id.ToString());

            //this.ClearFields();

        }

        private Guid Save()
        {
            string noticeId = HttpContext.Current.Request.QueryString["id"];
            String rootDir = SiteUtil.GetNoticesFilePath();

            NoticeDataSet notice = GetFields(noticeId, rootDir);
            NoticeRow noticeRow = notice.Notifications.Rows[0] as NoticeRow;
            bool added = noticeRow.RowState == System.Data.DataRowState.Added;
            int cnt = PublicAffair.BusinessActions.Notification.Update(notice);

            if (added)
            {
                SendSms(noticeRow.Accepter, noticeRow.Name);
            }

            return (notice.Notifications.Rows[0] as NoticeRow).Id;
        }

        protected void btnContinue_Click(object sender, EventArgs e)
        {

        }

        private void SetFields(string id)
        {
            if (!string.IsNullOrEmpty(id))
            {
                NoticeRow notice = CentralOffice.PublicAffair.BusinessActions.Notification.GetById(new Guid(id));

                txtName.Text = notice.Name;
                //txtNoticeNumber.Text = notice.NoticeNumber;
                //txtQueryNumber.Text = notice.QueryNumber;
                ddlSignificant.SelectedValue = EnumUtil.GetInt32(SiteConstants.Significant, CategoryDataSourceType.Xml, notice.Significant).ToString();
                txtProfile.Text = notice.Profile;
                //txtIsTop.Text = notice.IsTop;
                //txtAccepter.Text = notice.Accepter;
                //txtPublishDate.Text = notice.PublishDate;
                //txtStatus.Text = notice.Status;
                
                chkAll.Checked = notice.ReceiverType == 1;
                if (!chkAll.Checked)
                {
                    txtAccepter.Value = notice.Accepter;
                    txtAccepterReadOnly.Value = notice.Accepter;
                }
                

                txtContentText.Value = notice.ContentText;
            }
        }

        private NoticeDataSet GetFields(string id, string rootDir)
        {
            NoticeRow notice = null;

            if (String.IsNullOrEmpty(id))
            {
                notice = (new NoticeDataSet()).Notifications.NewNotificationsRow();
                SiteUtil.PopulateCommonField(notice, Guid.NewGuid());
                //notice.PublishDate = DateTime.Now;
            }
            else
            {
                // update
                notice = CentralOffice.PublicAffair.BusinessActions.Notification.GetById(new Guid(id));
            }

            notice.Name = txtName.Text;
            //notice.NoticeNumber = txtNoticeNumber.Text;
            notice.QueryNumber = CommonUtil.GetChineseSpell(txtName.Text);
            notice.Significant = ddlSignificant.SelectedItem.Text;
            notice.Profile = txtProfile.Text;
            notice.ReceiverType = chkAll.Checked ? 1 : 0;

            if (chkAll.Checked)
            {
                notice.Accepter = GetEmplyeeListString();
            }
            else
            {
                notice.Accepter = txtAccepter.Value;
            }
            notice.IsTop = false;
            //notice.Accepter = txtAccepter.Text;
            if (String.IsNullOrEmpty(id))
            {
                notice.PublishDate = DateTime.Now;
            }
            else
            {
                notice.ModifiedTime = DateTime.Now;
                notice.LastModifiedBy = ApplicationContext.ActualUserId;
            }
            
            //notice.Status = txtStatus.Text;
            //notice.Attachments = FileUploadControl1.GetAttachments(rootDir);

            string fileName = SaveFile(SiteUtil.GetNoticesFilePath(), FileUpload1);
            if (fileName.Length > 0)
            {
                notice.Attachments = fileName;
            }

            notice.ContentText = txtContentText.Value;
            

            if (String.IsNullOrEmpty(id))
            {
                notice.Table.Rows.Add(notice);
            }

            return notice.Table.DataSet as NoticeDataSet;
        }

        private string SaveFile(string rootDir, FileUpload file)
        {
            string fileName = "";

            string path = Server.MapPath(rootDir);
            if (file.HasFile)
            {
                //file.SaveAs(path + file.FileName);
                //fileName = rootDir + file.FileName;
                var fn = SiteUtil.GetUploadFileName(path, file.FileName);
                file.SaveAs(fn);
                fileName = rootDir + fn.Substring(fn.LastIndexOf('\\') + 1);
            }
            else
            {

            }
            return fileName;
        }

        private void ClearFields()
        {
            txtName.Text = "";
            txtProfile.Text = "";
            txtContentText.Value = "";
        }



        #region 选择接收者

        protected void btnShowPopup_Click(object sender, EventArgs e)
        {
            string[] assignedBy = txtAccepter.Value.Split(',');

            tvEmp.Nodes.Clear();
            HumanResources.HumanResourcesHelper.PopulateEmployeeTree(tvEmp, true, assignedBy);

            updPnlDepartment.Update();
            mdlDetailView.Show();

        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            // 保存弹出窗口所更新的信息
            string departments = "";
            string departmentsId = "";

            if (tvEmp.CheckedNodes.Count > 0)
            {
                foreach (TreeNode node in tvEmp.CheckedNodes)
                {
                    if (!node.Text.StartsWith("["))
                    {
                        departments += node.Text + ",";
                        departmentsId += node.Value + ",";
                    }
                }
            }
            txtAccepterReadOnly.Value = departments.Trim(',');
            //txtAccepter.Value = departmentsId;
            txtAccepter.Value = departments.Trim(',');
        }

        protected void tvEmp_Load(object sender, EventArgs e)
        {
            this.tvEmp.Attributes.Add("OnClick", "OnTreeNodeChecked(event)");
        }

        #endregion

        private void SendSms(string receivers, string message)
        {
            SmsDataSet smsBody = null;
            SmsBodyRow smsbodyrow = (new SmsDataSet()).sms_body.Newsms_bodyRow();

            smsbodyrow.FromId = ApplicationContext.ActualUserId.ToString();
            smsbodyrow.SmsType = "1";
            smsbodyrow.Content = message;
            smsbodyrow.SendTime = DateTime.Now;
            smsbodyrow.RemindUrl = "无";
            smsbodyrow.sGuid = Guid.NewGuid().ToString();
            smsbodyrow.Table.Rows.Add(smsbodyrow);
            smsBody = smsbodyrow.Table.DataSet as SmsDataSet;

            CentralOffice.MyTable.BusinessActions.SmsBody.Update(smsBody);

            smsbodyrow = CentralOffice.MyTable.BusinessActions.SmsBody.GetById(new Guid(smsbodyrow.sGuid));
            SmsDataSet smsds = new SmsDataSet();
            List<MembershipUserEx> employees = UserManager.GetAllUsersWithEmp(1);

            string[] rs = receivers.Split(',');
            foreach (string receiver in rs)
            {
                if (receiver.Length == 0) continue;
                MembershipUserEx emp = employees.First(e => e.Name == receiver);
                SmsRow smsrowTmp = smsds.sms.NewsmsRow();

                smsrowTmp.ToId = emp.EmployeeId.ToString();
                smsrowTmp.RemindFlag = "0";
                smsrowTmp.DeleteFlag = "0";
                smsrowTmp.BodyId = smsbodyrow.BodyId;
                smsds.sms.Rows.Add(smsrowTmp);
            }
            CentralOffice.MyTable.BusinessActions.Sms.Update(smsds);
        }

        private static string GetEmplyeeListString()
        {
            List<MembershipUserEx> employees = UserManager.GetAllUsersWithEmp(1);
            string emps = "";
            foreach (MembershipUserEx emp in employees)
            {
                emps += emp.Name + ",";
            }

            return emps.TrimEnd(',');
        }

    }
}